<template>
	<view class="dance-compare">
		<!-- 头部 -->
		<view class="header">
			<text class="title">舞蹈动作对比</text>
			<text class="subtitle">AI智能评分系统</text>
		</view>
		
		<!-- 摄像头状态显示 -->
		<view class="camera-status" :class="cameraStatusClass">
			{{ cameraStatusText }}
		</view>
		
		<!-- 视频区域 -->
		<view class="video-section">
			<!-- 标准动作视频 -->
			<view class="standard-video" v-if="selectedCourse">
				<text class="video-label">标准动作</text>
				<video 
					:src="selectedCourse.video" 
					class="video-player"
					:controls="false"
					:autoplay="false"
					:loop="true"
					:muted="true"
					ref="standardVideo"
				></video>
			</view>
			
			<!-- 用户摄像头 -->
			<view class="user-camera">
				<text class="video-label">你的动作</text>
				<camera 
					device-position="front"
					flash="off"
					@initdone="onCameraReady"
					@error="onCameraError"
					class="camera-view"
					ref="camera"
				></camera>
				<canvas 
					canvas-id="poseCanvas" 
					class="pose-canvas"
					:style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
				></canvas>
			</view>
		</view>
		
		<!-- 分数面板 -->
		<view class="score-panel">
			<view class="score-display">
				<text class="score-label">当前得分</text>
				<text class="score-value">{{ currentScore }}</text>
				<view class="stars">{{ getStars(currentScore) }}</view>
			</view>
			
			<view class="similarity-display" v-if="similarity >= 0">
				<text class="similarity-label">相似度</text>
				<text class="similarity-value">{{ similarity }}%</text>
			</view>
			
			<view class="feedback">
				<text v-for="(item, index) in feedback" :key="index" class="feedback-item">
					{{ item }}
				</text>
			</view>
		</view>
		
		<!-- 控制按钮 -->
		<view class="controls">
			<button 
				class="btn btn-primary" 
				@click="startComparison"
				:disabled="!canStart || isComparing"
			>
				{{ isComparing ? '⏸️ 暂停对比' : '🎯 开始对比' }}
			</button>
			
			<button 
				class="btn btn-secondary" 
				@click="resetComparison"
				:disabled="!isComparing && currentScore === 0"
			>
				🔄 重置
			</button>
			
			<button 
				class="btn btn-success" 
				@click="shareScore"
				:disabled="currentScore === 0"
			>
				📤 分享成绩
			</button>
		</view>
		
		<!-- 课程选择按钮 -->
		<view class="course-selector">
			<button class="btn btn-outline" @click="showCourseList = true">
				{{ selectedCourse ? selectedCourse.name : '选择舞蹈课程' }}
			</button>
		</view>
		
		<!-- 课程选择弹窗 -->
		<view class="course-popup" v-if="showCourseList" @click="showCourseList = false">
			<view class="popup-content" @click.stop>
				<view class="popup-header">
					<text class="popup-title">选择舞蹈课程</text>
					<text class="popup-close" @click="showCourseList = false">✕</text>
				</view>
				
				<scroll-view class="course-list" scroll-y>
					<view 
						class="course-item" 
						v-for="course in courseList" 
						:key="course.id"
						@click="selectCourse(course)"
					>
						<image :src="course.thumbnail" class="course-thumb"></image>
						<view class="course-info">
							<text class="course-name">{{ course.name }}</text>
							<text class="course-desc">{{ course.description }}</text>
							<view class="course-meta">
								<text class="course-difficulty">{{ course.difficulty }}</text>
								<text class="course-duration">{{ course.duration }}</text>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			// 摄像头状态
			cameraReady: false,
			cameraStatusText: '正在初始化摄像头...',
			cameraStatusClass: 'loading',
			
			// MediaPipe相关
			pose: null,
			camera: null,
			canvasCtx: null,
			canvasWidth: 300,
			canvasHeight: 400,
			
			// 对比状态
			isComparing: false,
			canStart: false,
			
			// 分数和反馈
			currentScore: 0,
			similarity: -1,
			feedback: ['等待开始对比...'],
			
			// 课程相关
			selectedCourse: null,
			showCourseList: false,
			courseList: [
				{
					id: 1,
					name: '基础芭蕾',
					description: '优雅的芭蕾基础动作练习',
					difficulty: '初级',
					duration: '3分钟',
					thumbnail: '/static/images/ballet-thumb.jpg',
					video: '/static/videos/ballet-basic.mp4',
					standardPose: null
				},
				{
					id: 2,
					name: '街舞基础',
					description: '动感街舞入门动作',
					difficulty: '初级',
					duration: '4分钟',
					thumbnail: '/static/images/hiphop-thumb.jpg',
					video: '/static/videos/hiphop-basic.mp4',
					standardPose: null
				},
				{
					id: 3,
					name: '现代舞表达',
					description: '情感丰富的现代舞蹈',
					difficulty: '中级',
					duration: '5分钟',
					thumbnail: '/static/images/modern-thumb.jpg',
					video: '/static/videos/modern-basic.mp4',
					standardPose: null
				}
			]
		}
	},
	
	async onLoad() {
		await this.initMediaPipe();
	},
	
	methods: {
		/**
		 * 初始化MediaPipe
		 */
		async initMediaPipe() {
			try {
				this.cameraStatusText = '正在加载AI模型...';
				this.cameraStatusClass = 'loading';
				
				// 在H5环境下使用MediaPipe
				// #ifdef H5
				const script = document.createElement('script');
				script.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/pose/pose.js';
				document.head.appendChild(script);
				
				script.onload = () => {
					this.pose = new Pose({
						locateFile: (file) => {
							return `https://cdn.jsdelivr.net/npm/@mediapipe/pose/${file}`;
						}
					});
					
					this.pose.setOptions({
						modelComplexity: 1,
						smoothLandmarks: true,
						enableSegmentation: false,
						minDetectionConfidence: 0.5,
						minTrackingConfidence: 0.5
					});
					
					this.pose.onResults(this.onPoseResults);
					this.cameraStatusText = 'AI模型加载完成';
					this.cameraStatusClass = 'success';
				};
				// #endif
				
				// #ifdef APP-PLUS
				// 在APP中可能需要使用原生插件或其他方案
				this.cameraStatusText = 'APP环境暂不支持，请使用H5版本';
				this.cameraStatusClass = 'error';
				// #endif
				
			} catch (error) {
				console.error('MediaPipe初始化失败:', error);
				this.cameraStatusText = '模型加载失败，请刷新重试';
				this.cameraStatusClass = 'error';
			}
		},
		
		/**
		 * 摄像头准备就绪
		 */
		onCameraReady() {
			this.cameraReady = true;
			this.canStart = this.pose !== null;
			
			if (this.canStart) {
				this.cameraStatusText = '准备就绪';
				this.cameraStatusClass = 'success';
			}
			
			// 获取canvas上下文
			this.canvasCtx = uni.createCanvasContext('poseCanvas', this);
		},
		
		/**
		 * 摄像头错误
		 */
		onCameraError(error) {
			console.error('摄像头错误:', error);
			this.cameraStatusText = '摄像头访问失败';
			this.cameraStatusClass = 'error';
		},
		
		/**
		 * 处理姿态检测结果
		 */
		onPoseResults(results) {
			if (!this.canvasCtx || !this.isComparing) return;
			
			// 清空画布
			this.canvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			
			if (results.poseLandmarks) {
				// 绘制姿态关键点
				this.drawPose(results.poseLandmarks);
				
				// 分析姿态质量
				const analysis = this.analyzePoseQuality(results.poseLandmarks);
				this.currentScore = analysis.score;
				this.feedback = analysis.feedback;
				
				// 如果有标准姿态，计算相似度
				if (this.selectedCourse && this.selectedCourse.standardPose) {
					this.similarity = this.calculateSimilarity(
						results.poseLandmarks, 
						this.selectedCourse.standardPose
					);
				}
			}
			
			this.canvasCtx.draw();
		},
		
		/**
		 * 绘制姿态关键点
		 */
		drawPose(landmarks) {
			// 连接线定义
			const connections = [
				[11, 12], [11, 23], [12, 24], [23, 24], // 身体中线
				[11, 13], [13, 15], // 左臂
				[12, 14], [14, 16], // 右臂
				[23, 25], [25, 27], // 左腿
				[24, 26], [26, 28]  // 右腿
			];
			
			// 绘制连接线
			this.canvasCtx.setStrokeStyle('#00FF00');
			this.canvasCtx.setLineWidth(3);
			
			connections.forEach(([start, end]) => {
				const startPoint = landmarks[start];
				const endPoint = landmarks[end];
				
				if (startPoint.visibility > 0.5 && endPoint.visibility > 0.5) {
					this.canvasCtx.beginPath();
					this.canvasCtx.moveTo(
						startPoint.x * this.canvasWidth,
						startPoint.y * this.canvasHeight
					);
					this.canvasCtx.lineTo(
						endPoint.x * this.canvasWidth,
						endPoint.y * this.canvasHeight
					);
					this.canvasCtx.stroke();
				}
			});
			
			// 绘制关键点
			this.canvasCtx.setFillStyle('#FF0000');
			landmarks.forEach((landmark) => {
				if (landmark.visibility > 0.5) {
					this.canvasCtx.beginPath();
					this.canvasCtx.arc(
						landmark.x * this.canvasWidth,
						landmark.y * this.canvasHeight,
						5, 0, 2 * Math.PI
					);
					this.canvasCtx.fill();
				}
			});
		},
		
		/**
		 * 分析姿态质量
		 */
		analyzePoseQuality(landmarks) {
			let score = 0;
			const feedback = [];
			
			// 检查姿态完整性
			const visibleKeypoints = landmarks.filter(kp => kp.visibility > 0.5);
			const completeness = visibleKeypoints.length / landmarks.length;
			
			if (completeness > 0.8) {
				score += 30;
				feedback.push('✅ 姿态检测完整');
			} else if (completeness > 0.6) {
				score += 20;
				feedback.push('⚠️ 部分身体部位不清晰');
			} else {
				feedback.push('❌ 请调整姿势，确保身体完整可见');
			}
			
			// 检查身体平衡
			const leftShoulder = landmarks[11];
			const rightShoulder = landmarks[12];
			
			if (leftShoulder.visibility > 0.5 && rightShoulder.visibility > 0.5) {
				const shoulderBalance = Math.abs(leftShoulder.y - rightShoulder.y);
				
				if (shoulderBalance < 0.05) {
					score += 35;
					feedback.push('✅ 身体平衡优秀');
				} else if (shoulderBalance < 0.1) {
					score += 25;
					feedback.push('⚠️ 身体稍有倾斜');
				} else {
					score += 10;
					feedback.push('❌ 注意身体平衡');
				}
			}
			
			// 检查手臂协调性
			const leftWrist = landmarks[15];
			const rightWrist = landmarks[16];
			
			if (leftWrist.visibility > 0.5 && rightWrist.visibility > 0.5) {
				score += 35;
				feedback.push('✅ 手臂动作清晰');
			} else {
				score += 15;
				feedback.push('⚠️ 手臂动作需要更清晰');
			}
			
			return {
				score: Math.min(score, 100),
				feedback: feedback
			};
		},
		
		/**
		 * 开始对比
		 */
		startComparison() {
			if (!this.canStart) return;
			
			this.isComparing = !this.isComparing;
			
			if (this.isComparing) {
				this.feedback = ['正在分析动作...'];
				this.currentScore = 0;
				this.similarity = -1;
			} else {
				this.feedback = ['对比已暂停'];
			}
		},
		
		/**
		 * 重置对比
		 */
		resetComparison() {
			this.isComparing = false;
			this.currentScore = 0;
			this.similarity = -1;
			this.feedback = ['等待开始对比...'];
			
			if (this.canvasCtx) {
				this.canvasCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
				this.canvasCtx.draw();
			}
		},
		
		/**
		 * 选择课程
		 */
		selectCourse(course) {
			this.selectedCourse = course;
			this.showCourseList = false;
			this.resetComparison();
		},
		
		/**
		 * 获取星级显示
		 */
		getStars(score) {
			const stars = Math.floor(score / 20);
			return '⭐'.repeat(stars) + '☆'.repeat(5 - stars);
		},
		
		/**
		 * 分享成绩
		 */
		shareScore() {
			const shareText = `我在舞蹈AI评分系统中获得了${this.currentScore}分！${this.getStars(this.currentScore)}`;
			
			uni.setClipboardData({
				data: shareText,
				success: () => {
					uni.showToast({ title: '成绩已复制到剪贴板', icon: 'success' });
				}
			});
		}
	}
}
</script>

<style scoped>
.dance-compare {
	padding: 20rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	min-height: 100vh;
}

.header {
	text-align: center;
	margin-bottom: 30rpx;
	color: white;
}

.title {
	font-size: 48rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 10rpx;
}

.subtitle {
	font-size: 28rpx;
	opacity: 0.8;
}

.camera-status {
	padding: 20rpx;
	border-radius: 15rpx;
	text-align: center;
	margin-bottom: 30rpx;
	font-size: 28rpx;
	font-weight: bold;
}

.camera-status.loading {
	background: linear-gradient(45deg, #ffd89b 0%, #19547b 100%);
	color: white;
}

.camera-status.success {
	background: linear-gradient(45deg, #56ab2f 0%, #a8e6cf 100%);
	color: white;
}

.camera-status.error {
	background: linear-gradient(45deg, #ff416c 0%, #ff4b2b 100%);
	color: white;
}

.video-section {
	display: flex;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.standard-video, .user-camera {
	flex: 1;
	position: relative;
}

.video-label {
	position: absolute;
	top: 10rpx;
	left: 10rpx;
	background: rgba(0, 0, 0, 0.7);
	color: white;
	padding: 10rpx 20rpx;
	border-radius: 10rpx;
	font-size: 24rpx;
	z-index: 10;
}

.video-player, .camera-view {
	width: 100%;
	height: 400rpx;
	border-radius: 15rpx;
	background: #f0f0f0;
}

.pose-canvas {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	pointer-events: none;
}

.score-panel {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	text-align: center;
}

.score-display {
	margin-bottom: 20rpx;
}

.score-label {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.score-value {
	font-size: 72rpx;
	font-weight: bold;
	color: #333;
	display: block;
}

.stars {
	font-size: 48rpx;
	margin: 20rpx 0;
}

.similarity-display {
	margin-bottom: 20rpx;
	padding: 20rpx;
	background: rgba(0, 123, 255, 0.1);
	border-radius: 10rpx;
}

.similarity-label {
	font-size: 24rpx;
	color: #666;
	display: block;
}

.similarity-value {
	font-size: 36rpx;
	font-weight: bold;
	color: #007bff;
}

.feedback {
	background: rgba(255, 255, 255, 0.8);
	border-radius: 15rpx;
	padding: 20rpx;
	margin: 20rpx 0;
	max-height: 200rpx;
	overflow-y: auto;
	text-align: left;
}

.feedback-item {
	display: block;
	margin-bottom: 10rpx;
	font-size: 28rpx;
	line-height: 1.5;
}

.controls {
	display: flex;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.btn {
	flex: 1;
	padding: 25rpx;
	border-radius: 15rpx;
	font-size: 28rpx;
	font-weight: bold;
	border: none;
	color: white;
}

.btn-primary {
	background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
}

.btn-secondary {
	background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
}

.btn-success {
	background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
}

.btn-outline {
	background: rgba(255, 255, 255, 0.9);
	color: #333;
	border: 2rpx solid #ddd;
}

.btn:disabled {
	opacity: 0.5;
	background: #ccc !important;
}

.course-selector {
	margin-bottom: 30rpx;
}

.course-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.popup-content {
	background: white;
	border-radius: 20rpx;
	width: 90%;
	max-height: 80%;
	overflow: hidden;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.popup-title {
	font-size: 36rpx;
	font-weight: bold;
}

.popup-close {
	font-size: 48rpx;
	color: #999;
}

.course-list {
	max-height: 600rpx;
}

.course-item {
	display: flex;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
	align-items: center;
}

.course-thumb {
	width: 120rpx;
	height: 120rpx;
	border-radius: 15rpx;
	margin-right: 30rpx;
}

.course-info {
	flex: 1;
}

.course-name {
	font-size: 32rpx;
	font-weight: bold;
	display: block;
	margin-bottom: 10rpx;
}

.course-desc {
	font-size: 28rpx;
	color: #666;
	display: block;
	margin-bottom: 10rpx;
}

.course-meta {
	display: flex;
	gap: 20rpx;
}

.course-difficulty, .course-duration {
	font-size: 24rpx;
	padding: 8rpx 16rpx;
	border-radius: 8rpx;
	background: #f0f0f0;
	color: #666;
}
</style> 